﻿using System;
using System.Linq;
using System.Threading;
using System.Web;

public partial class _Default : System.Web.UI.Page
{
    const string OPERATION_OPEN = "open";
    const string OPERATION_CHECK = "check";

    private CabAsyncResult asyncResult;
    private string portName;
    private string cmdCheck;
    private string cmdOpen;
    private string operation;
    private string result;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            Response.ContentType = "text/plain";
            if (Request.QueryString.AllKeys.Contains("operation"))
            {
                //操作类型
                operation = Request.QueryString.GetValues("operation")[0];
                //串口名称
                portName = Request.QueryString.GetValues("portName")[0];
               
                if (OPERATION_OPEN.Equals(operation))
                {
                    //开柜命令
                    cmdOpen = Request.QueryString.GetValues("cmdOpen")[0];
                    //执行开柜命令
                    if (!CabCtlLib.CabCtl.OpenCab(portName, cmdOpen))
                    {
                        ReturnError();
                    }
                    else
                    {
                        Response.Write("1");
                    }
                }
                else if (OPERATION_CHECK.Equals(operation))
                {
                    //检测命令
                    cmdCheck = Request.QueryString.GetValues("cmdCheck")[0];
                    //添加异步任务
                    this.AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginTask), new EndEventHandler(EndTask));
                }
                else
                {
                    //异常
                    ReturnError();
                }
            }
            else
            {
                //默认显示：服务正在运行。。。
                Response.Write("CAB-CTL-SERVER IS RUNNING...");
            }
        }
        catch(Exception ex)
        {
            CabCtlLib.Log.Write(ex.Message+"\n"+ ex.StackTrace);
            //异常
            ReturnError();
        }
    }

    /// <summary>
    /// 开始任务
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <param name="cb"></param>
    /// <param name="state"></param>
    /// <returns></returns>
    private IAsyncResult BeginTask(object sender, EventArgs e, AsyncCallback cb, object state)
    {
        CabCtlLib.Log.Write("#####BeginTask#####");
        asyncResult = new CabAsyncResult(cb);
        CabCtlLib.CabCtl.Received += CabCtl_Received;

        //执行状态检测命令
        if (!CabCtlLib.CabCtl.CheckCab(portName, cmdCheck))
        {
            ReturnError();
            asyncResult.SetComplete();
        }
        
        return asyncResult;
    }

    /// <summary>
    /// 结束任务
    /// </summary>
    /// <param name="ar"></param>
    private void EndTask(IAsyncResult ar)
    {
    }

    /// <summary>
    /// 接受状态检测结果
    /// </summary>
    /// <param name="cabLockStatus">快递柜开闭状态</param>
    private void CabCtl_Received(string cabLockStatus)
    {
        try
        {
            CabCtlLib.Log.Write("#####CabCtl_Received#####");
            CabCtlLib.Log.Write("cabLockStatus:" + cabLockStatus);

            CabCtlLib.CabCtl.Received -= CabCtl_Received;
            Response.Write(cabLockStatus);
            asyncResult.SetComplete();
        }
        catch(Exception ex)
        {
            CabCtlLib.Log.Write(ex.Message + "\n" + ex.StackTrace+ex.Source);
        }
        finally
        {
            ReturnError();
            asyncResult.SetComplete();
        }
    }

    private void ReturnError()
    {
        Response.Write("ERROR");
        Response.Close();
    }
}

class CabAsyncResult : IAsyncResult
{
    private AsyncCallback _callback;

    public CabAsyncResult(AsyncCallback cb)
    {
        _callback = cb;
    }

    //当异步完成时调用该方法
    public void SetComplete()
    {
        IsCompleted = true;
        if (_callback != null)
        {
            _callback(this);
        }
    }

    public object AsyncState
    {
        get { return null; }
    }

    //由于ASP.NET不会等待WEB异步方法，所以不使用此对象
    public WaitHandle AsyncWaitHandle
    {
        get { throw new NotImplementedException(); }
    }

    public bool CompletedSynchronously
    {
        get { return false; }
    }

    public bool IsCompleted
    {
        get;
        private set;
    }
}